package com.qzimp.fujiancuo.service.impl;

import com.qzimp.fujiancuo.config.MinioFile;
import com.qzimp.fujiancuo.mapper.FileUpLoadMapper;
import com.qzimp.fujiancuo.service.FileUpLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class FileUpLoadServiceImpl implements FileUpLoadService {

    @Autowired
    private FileUpLoadMapper fileUpLoadMapper;

    @Value("${mycuo.file-path}")
    private String dirPath;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 访问链接
     */
    @Override
    public String upLoad(MultipartFile file) throws IOException {
        MinioFile minioFile = new MinioFile();
        String originalFilename = file.getOriginalFilename();
        String filename = file.getOriginalFilename();

        String name = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));

        File file1 = new File(dirPath + name);
        file.transferTo(file1);
        String uriString = ServletUriComponentsBuilder.fromCurrentContextPath().path(name).toUriString();

        minioFile.setOriginalName(originalFilename);
        minioFile.setFilePath(uriString);
        minioFile.setDomain(uriString);
        minioFile.setHash(file1.hashCode() + "");
        minioFile.setName(dirPath + name);
        minioFile.setSize(file1.length());
        minioFile.setPutTime(LocalDateTime.now());
        minioFile.setContentType("image/jpeg");

        int insert = fileUpLoadMapper.insert(minioFile);
        if (insert > 0)
            return uriString;
        return "";
    }

}
